// 获取VSCode API
const vscode = acquireVsCodeApi();

// 存储当前状态
let state = {
    servers: [],
    selectedServer: null,
    selectedServerTools: []
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 注册按钮点击事件
    document.getElementById('add-server').addEventListener('click', addServer);
    document.getElementById('refresh').addEventListener('click', refreshServers);
    document.getElementById('back-to-chat').addEventListener('click', () => {
        // 发送消息到扩展
        vscode.postMessage({
          type: 'action',
          action: 'backToChat'
        });
      });

    // 请求获取服务器列表
    vscode.postMessage({ command: 'getServers' });

    // 监听来自扩展的消息
    window.addEventListener('message', handleMessage);
});

/**
 * 处理扩展发送的消息
 */
function handleMessage(event) {
    const message = event.data;

    switch (message.command) {
        case 'serversData':
            // 更新服务器列表
            updateServersList(message.servers);
            break;

        case 'serverToolsData':
            // 更新工具列表
            updateToolsList(message.serverName, message.tools);
            break;

        case 'error':
            // 显示错误消息
            showError(message.message);
            break;
        case 'action':
            if (message.action === 'showMcpConfig') {
                // 显示MCP配置界面
                document.getElementById('mcp-config-container').style.display = 'block';
                updateServersList(message.servers);
            }
            break;
    }
}

/**
 * 更新服务器列表
 */
function updateServersList(servers) {
    state.servers = servers || [];
    const serversListEl = document.getElementById('servers-list');

    // 清空列表
    serversListEl.innerHTML = '';

    if (!servers || servers.length === 0) {
        serversListEl.innerHTML = '<div class="empty-message">没有可用的MCP服务器</div>';
        return;
    }

    // 添加每个服务器的卡片
    servers.forEach(server => {
        const serverEl = document.createElement('div');
        serverEl.className = `server-card ${server.status} ${server.disabled ? 'disabled' : ''}`;
        serverEl.dataset.name = server.name;

        const isConnected = server.status === 'connected';
        const statusText = server.disabled ? '已禁用' :
            (server.status === 'connected' ? '已连接' :
                (server.status === 'connecting' ? '正在连接' : '已断开'));

        serverEl.innerHTML = `
            <div class="server-header">
                <div class="server-name">${server.name}</div>
                <div class="server-status ${server.status}">${statusText}</div>
            </div>
            
            <div class="server-actions">
                <button class="server-toggle ${server.disabled ? 'enable' : 'disable'}" title="${server.disabled ? '启用' : '禁用'}服务器">
                    ${server.disabled ? '启用' : '禁用'}
                </button>
                <button class="server-tools" title="查看工具" ${!isConnected ? 'disabled' : ''}>
                    工具
                </button>
                <button class="server-config" title="配置服务器">
                    配置
                </button>
                <button class="server-delete" title="删除服务器">
                    删除
                </button>
            </div>
            
            ${server.error ? `<div class="server-error">${server.error}</div>` : ''}
        `;

        // 添加按钮事件
        const toggleBtn = serverEl.querySelector('.server-toggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                toggleServer(server.name, server.disabled);
            });
        }

        const toolsBtn = serverEl.querySelector('.server-tools');
        if (toolsBtn && isConnected) {
            toolsBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                getServerTools(server.name);
            });
        }

        const configBtn = serverEl.querySelector('.server-config');
        if (configBtn) {
            configBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                openServerConfig();
            });
        }

        const deleteBtn = serverEl.querySelector('.server-delete');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                deleteServer(server.name);
            });
        }

        // 点击卡片时选中服务器
        serverEl.addEventListener('click', () => {
            if (isConnected) {
                selectServer(server.name);
            }
        });

        serversListEl.appendChild(serverEl);
    });
}

/**
 * 更新工具列表
 */
function updateToolsList(serverName, tools) {
    state.selectedServer = serverName;
    state.selectedServerTools = tools || [];

    const toolsListEl = document.getElementById('tools-list');

    // 清空列表
    toolsListEl.innerHTML = '';

    if (!tools || tools.length === 0) {
        toolsListEl.innerHTML = '<div class="empty-message">该服务器没有可用的工具</div>';
        return;
    }

    // 添加工具列表标题
    const titleEl = document.createElement('div');
    titleEl.className = 'tools-title';
    titleEl.textContent = `${serverName} 的工具`;
    toolsListEl.appendChild(titleEl);

    // 控制按钮容器
    const controlsEl = document.createElement('div');
    controlsEl.className = 'tools-controls';
    controlsEl.innerHTML = `
        <button id="auto-approve-all" class="button small">全部自动批准</button>
        <button id="manual-approve-all" class="button small">全部手动批准</button>
    `;

    // 添加自动批准全部按钮事件
    controlsEl.querySelector('#auto-approve-all').addEventListener('click', () => {
        const toolNames = tools.map(tool => tool.name);
        toggleToolsAutoApprove(serverName, toolNames, true);
    });

    // 添加手动批准全部按钮事件
    controlsEl.querySelector('#manual-approve-all').addEventListener('click', () => {
        const toolNames = tools.map(tool => tool.name);
        toggleToolsAutoApprove(serverName, toolNames, false);
    });

    toolsListEl.appendChild(controlsEl);

    // 添加工具列表
    const listEl = document.createElement('div');
    listEl.className = 'tools-list';

    tools.forEach(tool => {
        const toolEl = document.createElement('div');
        toolEl.className = 'tool-item';

        toolEl.innerHTML = `
            <div class="tool-info">
                <div class="tool-name">${tool.name}</div>
                ${tool.description ? `<div class="tool-description">${tool.description}</div>` : ''}
            </div>
            <div class="tool-auto-approve ${tool.autoApprove ? 'enabled' : 'disabled'}">
                ${tool.autoApprove ? '自动批准' : '手动批准'}
            </div>
        `;

        // 点击切换自动批准状态
        toolEl.addEventListener('click', () => {
            toggleToolsAutoApprove(serverName, [tool.name], !tool.autoApprove);
        });

        listEl.appendChild(toolEl);
    });

    toolsListEl.appendChild(listEl);
}

/**
 * 刷新服务器列表
 */
function refreshServers() {
    vscode.postMessage({ command: 'getServers' });
    
    // 显示刷新信息
    vscode.postMessage({ 
        command: 'showInformation',
        message: '正在刷新服务器列表...'
    });

    // 清空工具列表
    const toolsListEl = document.getElementById('tools-list');
    toolsListEl.innerHTML = '<div class="loading">选择服务器查看工具</div>';

    state.selectedServer = null;
    state.selectedServerTools = [];
}

/**
 * 添加服务器
 */
function addServer() {
    vscode.postMessage({ command: 'addServer' });
    
    // 显示添加服务器信息
    vscode.postMessage({ 
        command: 'showInformation',
        message: '请配置新服务器...'
    });
}

/**
 * 删除服务器
 */
function deleteServer(serverName) {
    vscode.postMessage({
        command: 'deleteServer',
        serverName
    });

    if (state.selectedServer === serverName) {
        // 清空工具列表
        const toolsListEl = document.getElementById('tools-list');
        toolsListEl.innerHTML = '<div class="loading">选择服务器查看工具</div>';

        state.selectedServer = null;
        state.selectedServerTools = [];
    }
}

/**
 * 启用/禁用服务器
 */
function toggleServer(serverName, isDisabled) {
    vscode.postMessage({
        command: 'toggleServer',
        serverName,
        enabled: isDisabled
    });
}

/**
 * 获取服务器工具
 */
function getServerTools(serverName) {
    vscode.postMessage({
        command: 'getServerTools',
        serverName
    });

    // 显示加载中状态
    const toolsListEl = document.getElementById('tools-list');
    toolsListEl.innerHTML = '<div class="loading">正在加载工具...</div>';

    // 处理服务器选中状态
    selectServer(serverName);
}

/**
 * 选中服务器
 */
function selectServer(serverName) {
    // 移除所有服务器的选中状态
    document.querySelectorAll('.server-card').forEach(el => {
        el.classList.remove('selected');
    });

    // 添加选中状态
    const serverEl = document.querySelector(`.server-card[data-name="${serverName}"]`);
    if (serverEl) {
        serverEl.classList.add('selected');
    }

    // 查询该服务器的工具
    if (state.selectedServer !== serverName) {
        getServerTools(serverName);
    }
}

/**
 * 打开服务器配置
 */
function openServerConfig() {
    vscode.postMessage({ command: 'openConfig' });
}

/**
 * 切换工具自动批准设置
 */
function toggleToolsAutoApprove(serverName, toolNames, autoApprove) {
    vscode.postMessage({
        command: 'toggleToolAutoApprove',
        serverName,
        toolNames,
        autoApprove
    });
}

/**
 * 显示错误消息
 */
function showError(message) {
    console.error('错误:', message);

    // 在界面上显示错误信息（临时实现）
    const errorEl = document.createElement('div');
    errorEl.className = 'error-message';
    errorEl.textContent = message;

    document.body.appendChild(errorEl);

    // 3秒后自动消失
    setTimeout(() => {
        document.body.removeChild(errorEl);
    }, 3000);
} 